package com.jn.exam.ucenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.exam.JwtUtils;
import com.jn.exam.MD5Util;
import com.jn.exam.R;
import com.jn.exam.ucenter.entity.*;
import com.jn.exam.ucenter.service.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;

import static com.jn.exam.JwtUtils.APP_SECRET;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 江南大学1033190417
 * @since 2022-01-20
 */
@Api(description = "超管")
@RestController
@RequestMapping("/ucenter/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;


    @PostMapping("loginByNumber/{username}")
    public R login(@PathVariable("username") String username, String password) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username).eq("password", MD5Util.getMD5(password));
        Admin admin = adminService.getOne(wrapper);
        if (admin == null) {
            return R.error().message("登录失败");
        }
        String token = JwtUtils.getJwtToken(admin.getId(), admin.getUsername());
        return R.ok().message("登录成功").data("token", token);
    }

    @PostMapping("getUserInfo")
    public R getUserInfo(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String id = (String) claims.get("id");
        Admin admin = adminService.getById(id);
        return R.ok().data("admin", admin);
    }

    //退出登录
    @PostMapping("loginOut")
    public R loginOut(HttpServletRequest request) {
        return R.ok().message("退出登录成功");
    }

    @ApiOperation(value = "添加人脸库组")
    @PutMapping("addFaceGroup")
    public R addFaceGroup() {
        boolean isAdd = adminService.addFaceGroup();
        if (isAdd) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    @ApiOperation("查询人脸库组")
    @GetMapping("getFaceGroup")
    public R getFaceGroup(){
        List<String> groups=adminService.getFaceGroup();
        return R.ok().data("groups",groups);
    }




}

